package com.ellecity06.common.base

import android.app.Dialog
import android.os.Handler
import android.os.Looper
import android.util.DisplayMetrics
import android.view.Gravity
import android.view.View
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager


abstract class CustomDialog : DialogFragment() {


    var onItemClickListener: CustomDialog.OnItemClickListener? = null
    var onShowListener: CustomDialog.OnShowListener? = null
    var onDismissListener: CustomDialog.OnDismissListener? = null
    val mHandler: Handler = Handler(Looper.getMainLooper())

    open fun setOnItemClickListener(onItemClickListener: CustomDialog.OnItemClickListener): CustomDialog {
        this.onItemClickListener = onItemClickListener
        return this
    }

    open fun setOnClickListener(onItemClickListener: CustomDialog.OnItemClickListener): CustomDialog {
        this.onItemClickListener = onItemClickListener
        return this
    }

    interface OnItemClickListener {
        fun onItemClick(v: View)
    }

    open fun setOnShowListener(onShowListener: CustomDialog.OnShowListener): CustomDialog {
        this.onShowListener = onShowListener
        return this
    }

    interface OnShowListener {
        fun onShow()
    }

    open fun setOnDismissListener(onDismissListener: CustomDialog.OnDismissListener): CustomDialog {
        this.onDismissListener = onDismissListener
        return this
    }

    interface OnDismissListener {
        fun onDismiss()
    }

    open fun show(context: FragmentActivity): CustomDialog {
        return show(context.supportFragmentManager)
    }

    open fun show(manager: FragmentManager): CustomDialog {
        try {
            val dialog: Dialog? = dialog
            if (dialog == null || !dialog.isShowing) {
                manager.beginTransaction().remove(this).commit()
                show(manager, "dialog")
                //放在show()之后，不然有些属性是没有效果的，比如height和width
                val mDisplayMetrics = requireContext().resources.displayMetrics
                dialog?.window!!.attributes.width = mDisplayMetrics.widthPixels//设置宽度
                dialog?.window!!.attributes.gravity = Gravity.CENTER

            }
            if (onShowListener != null) {
                onShowListener!!.onShow()
            }
        } catch (e: Exception) {
        }
        return this
    }

    override fun dismiss() {
        try {
            if (onDismissListener != null) {
                onDismissListener!!.onDismiss()
            }
            super.dismiss()
        } catch (e: Exception) {
        }
    }


}